﻿using DeHeng_Mes.Constant;
using DeHeng_Mes.Model.Boss;
using DeHeng_Mes.Model.Table;
using DeHeng_Mes.Utils;
using System;
using System.Collections.Generic;

namespace DeHeng_Mes.Dao
{
    public class DeviceDao
    {
        /// <summary>
        /// 初始化报警信息
        /// </summary>
        /// <param name="deviceFault"></param>
        public void ErrorDataInit(DeviceFault deviceFault)
        {
            using (var db = SqlSugarConfig.Db)
            {
                db.Insertable(deviceFault).ExecuteCommand();

                Tools.ProduceLogText($"检测到一条报警信息，报警源{deviceFault.PlcName}，报警类型为{deviceFault.FaultType}，报警信息为{deviceFault.FaultMessage}，开始时间是{deviceFault.StopStartTime}");
            }
        }


        /// <summary>
        /// 处理故障结束时间
        /// </summary>
        /// <param name="deviceFault"></param>
        public void UpDateEndErrorTime(DeviceFault deviceFault)
        {
            using (var db = SqlSugarConfig.Db)
            {
                DateTime endTime = DateTime.Now;

                string timer = Tools.CalculateTimeDifferenceInMinutes(deviceFault.StopStartTime, endTime);

                db.Updateable<DeviceFault>()
                    .Where(x => x.StopStartTime == deviceFault.StopStartTime && x.FaultType == deviceFault.FaultType && x.FaultMessage == deviceFault.FaultMessage && x.PlcName == deviceFault.PlcName)
                    .SetColumns(x => new DeviceFault
                    {
                        StopEndTime = endTime,
                        FaultTime = timer
                    })
                    .ExecuteCommand();

                Tools.ProduceLogText($"故障结束处理，故障原信息{deviceFault.FaultMessage}，故障原开始时间{deviceFault.StopStartTime}，故障结束时间{deviceFault.StopStartTime}，持续时长{timer}");
            }
        }

        /// <summary>
        /// 获取看板需要的故障数据
        /// </summary>
        /// <param name="firstDayOfMonth"></param>
        /// <param name="lastDayOfMonth"></param>
        public List<DeviceFault> GetErrorData(DateTime today)
        {
            using (var db = SqlSugarConfig.Db)
            {
                List<DeviceFault> deviceFaults = db.Queryable<DeviceFault>()
                                                   .Where(x => x.StopStartTime >= today && x.StopStartTime < today.AddDays(1))
                                                   .ToList();

                return deviceFaults;
            }
        }
    }
}
